﻿
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Runtime.CompilerServices;
using System.Security.Claims;
using System.Text;

namespace JWTLogin.Controllers
{
    [Route("[controller]/[action]")]
    [Authorize]
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }

        public ActionResult Get()
        {
            var tokenHeader = HttpContext.Request.Headers["Authorization"].ToString().Replace("Bearer ", "");
            var jwthandler = new JwtSecurityTokenHandler();
            JwtSecurityToken jwtst = jwthandler.ReadJwtToken(tokenHeader);
            jwtst.Payload.TryGetValue(ClaimTypes.Name, out var name);
            return Ok("ok" + name);
        }

        [AllowAnonymous]
        public ActionResult Login()
        {
            //  LoginViewModel loginViewModel = new LoginViewModel();
            // loginViewModel.Username = "11";
            //验证用户名密码是否正确，错误则不进行后续操作
            // {
            //验证逻辑在此省略
            //  }
            //验证成功则继续运行后面代码，来生成token

            //claims是关于用户的一些信息，这部分信息将放在payload中，由于token可以被解密，因此不要把密码放进去
            var claims = new Claim[]
            {
                new Claim(ClaimTypes.Name, "11")
            };
            //指定生成token所需要的密钥
            SymmetricSecurityKey key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("bc47a26eb9a59406057dddd62d0898f4"));
            //指定数字签名需要使用的密钥和算法
            SigningCredentials credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            //生成token
            JwtSecurityToken token = new JwtSecurityToken(issuer: "xxx",//颁发者
                                                          audience: "xxx",//可以给哪些客户端使用
                                                          claims: claims,
                                                          notBefore: DateTime.Now, //token生效时间
                                                          expires: DateTime.Now.AddMinutes(5), //token有效时间
                                                          signingCredentials: credentials);


            //  string token new JwtSecurityTokenHandler().WriteToken(token)


            return Ok();
        }
    }
}
